package misty.mispic.app.comp

import javafx.fxml.FXML
import javafx.fxml.FXMLLoader
import javafx.fxml.Initializable
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.control.Tooltip
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import misty.mispic.app.event.EventBus
import misty.mispic.app.event.PhotoEvent
import misty.mispic.app.ui.FXML as Fxmls
import org.controlsfx.control.GridCell

import java.nio.file.Paths

/**
 * Created by Misty on 2015/1/25.
 */
class ThumbGridCell extends GridCell<Image> implements Initializable {
    @FXML
    private Node mRoot

    @FXML
    private Label mName

    @FXML
    private Label mImageContent

    private ImageView imageView

    private Tooltip tooltip


    private final boolean preserveImageProperties

    ThumbGridCell(boolean preserveImageProperties) {
        getStyleClass().add("thumb-grid-cell"); //$NON-NLS-1$

        imageView = new ImageView()
        tooltip = new Tooltip()

        def loader = new FXMLLoader(Fxmls.ThumbGridCell.location)
        loader.controller = this
        loader.load()

        this.preserveImageProperties = preserveImageProperties
    }

    ThumbGridCell() {
        this(true)
    }

    @Override
    void initialize(URL location, ResourceBundle resources) {
        imageView.fitWidthProperty().bind(mImageContent.widthProperty())
        imageView.fitHeightProperty().bind(mImageContent.heightProperty())
//        imageView.fitWidthProperty().addListener({
//            println "${imageView.fitWidth} * ${imageView.fitHeight}"
//        } as InvalidationListener)
        mImageContent.setGraphic(imageView)

        mRoot.onMouseClicked = { e ->
            if (e.clickCount == 2 && item) {
                EventBus.post(new PhotoEvent.Show(item))
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void updateItem(Image item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setTooltip(null)
            setGraphic(null);
        } else {
            setTooltip(tooltip)
            if (preserveImageProperties) {
                imageView.setPreserveRatio(item.isPreserveRatio())
                imageView.setSmooth(item.isSmooth())
            }
            setGraphic(mRoot)
            imageView.setImage(item)

            def url = new URL(item.impl_getUrl())
            def path = Paths.get(url.toURI())

            mName.setText(path.fileName.toString())
            tooltip.setText(path.toString())
        }
    }
}
